// loongarch64.rs
use super::Timer;
use loongArch64::register::ecfg::{self, LineBasedInterrupt};
use loongArch64::register::tcfg;
/// Returns the current clock time in hardware ticks.
use loongArch64::time::{Time, get_timer_freq};

const CLOCK_FREQ: usize = 100_000_000; // 典型LoongArch CPU频率
impl Timer {
    #[inline]
    pub fn get_cur_timer() -> usize {
        Time::read() as usize
    }

    pub fn timer_init() {
        let ticks = ((CLOCK_FREQ / 1000) + 3) & !3;
        tcfg::set_periodic(true);
        tcfg::set_init_val(ticks);
        tcfg::set_en(true);
        let inter = LineBasedInterrupt::TIMER
            | LineBasedInterrupt::SWI0
            | LineBasedInterrupt::SWI1
            | LineBasedInterrupt::HWI0;
        ecfg::set_lie(inter);
        crate::INFO!("Timer Init Done");
    }

    #[inline]
    pub fn set_next_timeout() {
        let next = Self::get_cur_timer().wrapping_add(CLOCK_FREQ / 100);
        tcfg::set_init_val(next);
    }
}
